package com.example.hongyu.avtt.ui.activity;

import static tv.danmaku.ijk.media.player.IMediaPlayer.MEDIA_INFO_BUFFERING_END;
import static tv.danmaku.ijk.media.player.IMediaPlayer.MEDIA_INFO_BUFFERING_START;
import static tv.danmaku.ijk.media.player.IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START;

import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;


import com.example.hongyu.avtt.R;
import com.example.hongyu.avtt.event.Event;
import com.example.hongyu.avtt.ui.base.BaseActivity;
import com.example.hongyu.avtt.ui.widget.AVLoadingIndicatorView;
import com.example.hongyu.avtt.ui.widget.ToastTool;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;


public class AlivePlayerActivity extends BaseActivity {
    @BindView(R.id.videoView)
    VideoView mVideoView;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.textViewName)
    TextView textViewName;
    @BindView(R.id.textViewTime)
    TextView textViewTime;
    @BindView(R.id.textViewCurrentPosition)
    TextView textViewCurrentPosition;
    @BindView(R.id.seek_layout)
    LinearLayout seekLayout;
    @BindView(R.id.loading_layout)
    LinearLayout loadingLayout;
    @BindView(R.id.avi)
    AVLoadingIndicatorView avLoadingIndicatorView;
    String name="";
    String url="";

    private Handler handler = new Handler();
    private Handler viewHandler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            if (mVideoView.isPlaying()) {
                int current = mVideoView.getCurrentPosition();
                seekBar.setProgress(current);
                textViewCurrentPosition.setText(time(mVideoView.getCurrentPosition()));
            }
            handler.postDelayed(runnable, 500);
        }
    };
    private Runnable viewRunnable = new Runnable() {
        public void run() {


            seekLayout.setVisibility(View.GONE);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initActivityData() {
        mBundle=getBundle();
        url=mBundle.getString("PLAYURL");
//        url="http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8";
        name= mBundle.getString("PLAYNAME");
        ToastTool.show(name);
        textViewName.setText(name);
        initVideoView();
    }

    @Override
    protected void initContentView() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        avLoadingIndicatorView.setIndicator("LineSpinFadeLoaderIndicator");
        loadingLayout.setVisibility(View.VISIBLE);
    }
    private void initVideoView(){
        // 为进度条添加进度更改事件
        seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
        mVideoView.setVideoPath(url);//设置视频文件
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                loadingLayout.setVisibility(View.GONE);
                textViewTime.setText(time(mVideoView.getDuration()));
                seekBar.setMax(mVideoView.getDuration());
                mVideoView.start();
                handler.postDelayed(viewRunnable, 1000);
                handler.postDelayed(runnable, 0);
            }
        });
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //视频播放完成后的回调

            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //异常回调
                return false;//如果方法处理了错误，则为true；否则为false。返回false或根本没有OnErrorListener，将导致调用OnCompletionListener。
            }
        });
        mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                switch (what){
                    case MEDIA_INFO_BUFFERING_START:
                        loadingLayout.setVisibility(View.VISIBLE);
                        break;
                    case  MEDIA_INFO_VIDEO_RENDERING_START:

                        break;
                    case MEDIA_INFO_BUFFERING_END:
                        loadingLayout.setVisibility(View.GONE);
                        break;
                }
                //信息回调
//                what 对应返回的值如下
//                public static final int MEDIA_INFO_UNKNOWN = 1;  媒体信息未知
//                public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 媒体信息视频跟踪滞后
//                public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3; 媒体信息\视频渲染\开始
//                public static final int MEDIA_INFO_BUFFERING_START = 701; 媒体信息缓冲启动
//                public static final int MEDIA_INFO_BUFFERING_END = 702; 媒体信息缓冲结束
//                public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703; 媒体信息网络带宽（703）
//                public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 媒体-信息-坏-交错
//                public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 媒体信息找不到
//                public static final int MEDIA_INFO_METADATA_UPDATE = 802; 媒体信息元数据更新
//                public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901; 媒体信息不支持字幕
//                public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902; 媒体信息字幕超时

                return false; //如果方法处理了信息，则为true；如果没有，则为false。返回false或根本没有OnInfoListener，将导致丢弃该信息。
            }
        });
        MediaController mediaController = new MediaController(this.getContext());
        mediaController.setMediaPlayer(mVideoView);

        mediaController.setPrevNextListeners(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                },
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                    }
                });


    }
    @OnClick({R.id.videoView})
    public  void onClick(View view){
        int id=view.getId();
        switch (id){
            case R.id.videoView:
                if (seekLayout.getVisibility()==View.GONE){
                    seekLayout.setVisibility(View.VISIBLE);
                    handler.postDelayed(viewRunnable, 1000);
                }

                break;
        }
    }
    protected String time(long millionSeconds) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(millionSeconds);
        return simpleDateFormat.format(c.getTime());
    }

    private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        // 当进度条停止修改的时候触发
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (mVideoView.isPlaying()) {
                // 设置当前播放的位置
                mVideoView.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {

        }
    };
    @Override
    protected int getContentView() {
        hideSystemBar();// 全屏设置
        return R.layout.activity_alive_player;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.suspend();
        }
        handler.removeCallbacks(runnable);
    }

    @Override
    protected void onEventProcess(Event event) {

    }
}